﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AdventureWorks.Entities;
using AdventureWorks.DAO;
using AdventureWorksData.DAO;
using AdventureWorks.Business;
using AdventureWorks.Exceptions;

namespace AdventureWorks.View.Controllers
{ 
    public class ProductModelController : Controller
    {
		private readonly ProductModelBusiness _buzz;

    	public ProductModelController()
    	{
			_buzz = new ProductModelBusiness();
    	}

		public ProductModelController(IUnitOfWork entityDb)
    	{
			_buzz = new ProductModelBusiness(entityDb);
    	}

		public ViewResult Index()
        {
        	var productModels = _buzz.GetList(String.Empty, String.Empty);
			return View(productModels);
        }

        public ViewResult Details(int id)
        {
            var productModel = _buzz.Get(id);
            return View(productModel);
        }

        public ActionResult Create()
        {
            return View();
        } 

        [HttpPost]
        public ActionResult Create(ProductModel productModel)
        {
            if (ModelState.IsValid)
            {
				_buzz.Insert(productModel);
                _buzz.Save();

                return RedirectToAction("Index");  
            }
            return View(productModel);
        }
 
        public ActionResult Edit(int id)
        {
            var productModel = _buzz.Get(id);
            return View(productModel);
        }

        [HttpPost]
        public ActionResult Edit(ProductModel productModel)
        {
            if (ModelState.IsValid)
            {
				productModel.ModifiedDate = DateTime.Now;
				_buzz.Update(productModel);
                _buzz.Save();

                return RedirectToAction("Index");
            }
            return View(productModel);
        }
 
        public ActionResult Delete(int id)
        {
			var productModel = _buzz.Get(id);
			return View(productModel);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
			try
			{
				_buzz.Delete(id);
				_buzz.Save();
			}
			catch(BusinessException ex)
			{
				ViewBag.ExceptionMessage = ex.Message;
				return Delete(id);
			}
			return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            _buzz.Dispose();
            base.Dispose(disposing);
        }
    }
}